import { Button, Space, Input, Cascader, Modal, Switch, message, Layout } from 'myselfantd';
import type { ColumnsType, TableProps } from 'antd/es/table';
import React, { useRef, useState, useCallback, useMemo, useImperativeHandle } from 'react';
import { getThresholdPage, getDeviceList, updateThresholdStatus } from '../api';
import type { getThresholdPageParams } from '../api';
import ThresholdForm from './ThresholdForm';
import _ from 'lodash';
interface DataType {
  code: number;
  machineTypeName: string;
  type: string;
  fieldCount: number;
  thresholdCount: number;
  status: number;
  remark: string;
}
interface Props {
  reload: number;
  title?: string;
  stateChange?: Function;
  pageRef?: any;
}
const App = ({ reload: tableReload, pageRef }: Props) => {
  const [showDialog, setVisible] = useState<any>([false, '', {}]);
  const ref = useRef<any>();
  useImperativeHandle(pageRef, () => {
    return {
      handleAdd: () => {
        setVisible([true, 'add', '']);
      }
    };
  });
  return (
    <>
      <Layout.PageContent
        pageContentRef={ref}
        search={useMemo(
          () => ({
            template: [
              {
                name: 'machineNameMt',
                render: () => <Input placeholder="请输入农机名称" />
              },
              {
                name: 'machineTypeCode',
                render: () => (
                  <Cascader
                    request={async () => {
                      let { result } = await getDeviceList({ category: 0 });
                      return result;
                    }}
                    fieldNames={{ label: 'name', value: 'id' }}
                    placeholder="选择农机类型"
                  />
                )
              }
            ]
          }),
          []
        )}
        table={useMemo(
          () => ({
            template: [
              {
                title: ' 序号 ',
                dataIndex: 'index',
                render: (text, record, index) => `${index + 1}`,
                width: 80
              },
              {
                title: '农机名称',
                dataIndex: 'machineName',
                key: 'machineName',
                showSorterTooltip: false
              },
              {
                title: '农机类型',
                dataIndex: 'machineTypeName',
                key: 'machineTypeName',
                showSorterTooltip: false,
                width: 180
              },
              {
                title: '可监控工况字段数量',
                dataIndex: 'fieldCount',
                key: 'fieldCount',
                showSorterTooltip: false,
                width: 180
              },
              {
                title: '设置阈值数量',
                dataIndex: 'thresholdCount',
                key: 'thresholdCount',
                showSorterTooltip: false,
                width: 150
              },
              {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                showSorterTooltip: false,
                width: 150,
                render: (_, record: any) => {
                  return (
                    <Switch
                      defaultChecked={_}
                      onChange={(status) => {
                        updateThresholdStatus({ status: +status, id: record.id }).then(
                          (res: any) => {
                            message.success('状态更新成功');
                            ref.current?.handleSearch();
                          }
                        );
                      }}
                    />
                  );
                }
              },
              // {
              //   title: '备注',
              //   dataIndex: 'remark',
              //   key: 'remark',
              //   showSorterTooltip: false,
              //   width: 250
              // },
              {
                title: '操作',
                key: 'action',
                width: 150,
                render: (_, record) => (
                  <Space size="middle">
                    <Button
                      type="link"
                      block
                      onClick={() => {
                        setVisible([true, 'edit', _]);
                      }}>
                      详情
                    </Button>
                  </Space>
                )
              }
            ] as ColumnsType<DataType>,
            data: {
              data: [] as ColumnsType<DataType>,
              page: { total: 0, pageSize: 10, current: 1 }
            }
          }),
          []
        )}
        // request={useCallback(async (page: any, params: any, callback: Function) => {
        //   params.machineTypeCode &&
        //     (params.machineTypeCode = params.machineTypeCode?.splice(-1)[0]);
        //   let defaultParams: any = {
        //     pageIndex: page.current,
        //     pageSize: page.pageSize
        //   };
        //   let {
        //     result: { data, pageIndex: newPageIndex, pageSize: newPageSize, total },
        //   } = await getThresholdPage({ ...defaultParams, ...params });
        //   return {
        //     data,
        //     page: { total, pageSize: newPageSize, current: newPageIndex }
        //   };
        // }, [])}
      />
      {showDialog[1] === 'add' && (
        <Modal.Dialog
          showDialog={showDialog[0]}
          changeDialog={(state: boolean) => setVisible([false, '', ''])}
          size="big">
          <ThresholdForm
            onFinish={() => {
              setVisible([false, '', {}]);
              ref.current?.handleSearch();
            }}
            type={'add'}
            title={'新增阈值报警'}
          />
        </Modal.Dialog>
      )}
      {showDialog[1] === 'edit' && (
        <Modal.Dialog
          showDialog={showDialog[0]}
          changeDialog={(state: boolean) => setVisible([false, '', ''])}
          size="big">
          <ThresholdForm
            onFinish={() => {
              setVisible([false, '', '']);
              ref.current?.handleSearch();
            }}
            data={showDialog[2]}
            type={'edit'}
            title={'阈值报警详情'}
          />
        </Modal.Dialog>
      )}
    </>
  );
};

export default App;
